//
//  DHStatusPictureView.swift
//  Weibo
//
//  Created by Holfioo on 15/9/8.
//  Copyright © 2015年 Holfioo. All rights reserved.
//

import UIKit
import SDWebImage

let DHPictureCellID = "DHPictureCellID"
let DHPhotoSelectedNotification = "DHPhotoSelectedNotification"
let DHPhotoSelectedIndexPathKey = "DHPhotoSelectedIndexPathKey"
let DHPhotoSelectedUrlsKey = "DHPhotoSelectedUrlsKey"

class DHStatusPictureView: UICollectionView {

    // 调用模型数据。
    var statusViewModel: DHStatusViewModel? {
        didSet {
            sizeToFit()
            // 刷新数据，只有新的cell 出现的时候才进入
            reloadData()
        }
    }
    // sizeToFit 调用 sizeThatFit
    override func sizeThatFits(size: CGSize) -> CGSize {
        return makePicSize()
    }
    
    // 计算视图的大小。
    private func makePicSize() -> CGSize {
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        // 设置 流水布局的 item的大小。
        layout.itemSize = CGSize(width: DHPictureItemWH, height: DHPictureItemWH)
        // 根据视图模型中的图片数组的count计算
        let count = statusViewModel?.thumbnailUrls?.count ?? 0 // 如果没有的话 就是0
        // 分几种情况讨论
        if count == 0 {
            return CGSizeZero
        }
        if count == 1 {
            // 每次优先从缓存读取数据
            var size = CGSize(width: 150, height: 150)
            // 这个KEY就是路径,取出全部字段
            let key = statusViewModel?.thumbnailUrls![0].absoluteString
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
                
                // 返回图片的大小！！！ 为了就是这个！
                size = image.size
            }
            // 判断图片的大小，过窄和过长的进行过滤
            size.width = size.width < 40 ? 40 : size.width
            size.height = size.height > 300 ? 300 : size.height
            
            layout.itemSize = size
            return size  // 临时数
        }
        if count == 4 {
            let wh = DHPictureItemWH * 2 + DHPictureItemMargin
            
            return CGSize(width: wh , height: wh)
        }
        // 其他情况。
        /// 返回的要是一个CGFloat 所以计算的过程中就要。
        let row = CGFloat((count - 1) / Int(DHPictuerMaxRowCount) + 1)
        let h = row * DHPictureItemWH + (row - 1) * DHPictureItemMargin
        let w = DHPictuerMaxWH
        return CGSize(width: w , height: h )
    }
        
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        // 一定记住是 FlowLayout!!!
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        backgroundColor = UIColor.whiteColor()
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        // 设置 布局的属性。间距。
        layout.minimumInteritemSpacing = DHPictureItemMargin
        layout.minimumLineSpacing = DHPictureItemMargin
        
        // 设置代理
        delegate = self
        dataSource = self
        registerClass(DHStatusPictureCell.self, forCellWithReuseIdentifier: DHPictureCellID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension DHStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    //MARK: - 代理 及 数据源方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 查看 indexPath 和 CV 的属性
        print(statusViewModel?.bmiddleUrls)
        // 注意此处。是强行解包
        NSNotificationCenter.defaultCenter().postNotificationName(DHPhotoSelectedNotification, object: self, userInfo: [DHPhotoSelectedIndexPathKey: indexPath,
            DHPhotoSelectedUrlsKey: statusViewModel!.bmiddleUrls!])
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statusViewModel?.thumbnailUrls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(DHPictureCellID, forIndexPath: indexPath) as! DHStatusPictureCell
        cell.imaUrl = statusViewModel!.thumbnailUrls![indexPath.item]
        
        return cell
    }
}

private class DHStatusPictureCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(iconView)
        iconView.ff_Fill(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 图片的URL 
    // 重写setter方法。
    var imaUrl: NSURL? {
        didSet {
            // 设置图片,用带占位图片的方法不好使
            iconView.sd_setImageWithURL(imaUrl, placeholderImage: UIImage(named: "Icon"))
        }
    }
    private lazy  var iconView: UIImageView = {
       let imaV = UIImageView()
        imaV.contentMode = UIViewContentMode.ScaleAspectFill
        imaV.clipsToBounds = true
        return imaV
    }()
}